/******************************************************************************
 *
 *  socket_tcp_fork_server.c
 *
 *  Created on: 2012-3-11
 *      Author: Michael
 *       Email: zhongchao.ustc@gmail.com
 *
 *  Copyright (c) Michael Chao Zhong
 *
 *****************************************************************************/

#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
	// Create socket
	int socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
	
	// Initialize server address
	struct hostent *server_host = gethostbyname(argv[1]);
	struct sockaddr_in server_addr;
	server_addr.sin_family = AF_INET; // socket internet family
	bcopy((char *)server_host->h_addr, (char *)&server_addr.sin_addr.s_addr,
			server_host->h_length); // socket internet address
	server_addr.sin_port = htons(atoi(argv[2])); // socket internet port
	printf("server_addr.sin_addr.s_addr = %u\n", server_addr.sin_addr.s_addr);

	// Send
	char buffer[1024];
	sendto(socket_fd, buffer, sizeof(buffer), 0,
			(const struct sockaddr *) &server_addr, sizeof(struct sockaddr_in));

	// Receive and write
	struct sockaddr_in client_addr;
	socklen_t client_addr_length = sizeof(client_addr);
	int msg_recv_length = recvfrom(socket_fd, buffer, sizeof(buffer), 0,
			(struct sockaddr *) &client_addr, &client_addr_length);
	printf("client_addr.sin_addr.s_addr = %u\n", client_addr.sin_addr.s_addr);
	const char *hint = "Got an ACK: ";
	write(1, hint, strlen(hint));
	write(1, buffer, msg_recv_length);

	// Close
	close(socket_fd);

	return 0;
}
